import React, { useEffect, useState } from 'react'
import ReactDOM from 'react-dom'
import TodoHeader from './pages/TodoHeader/index'
import TodoMain from './pages/TodoMain/index'
import TodoFooter from './pages/TodoFooter/index'
import './styles/base.css'
import './styles/index.css'
export const Context = React.createContext()

// 封装自定义hooks
function useTodos() {
  // useState()传的箭头函数只会执行一次
  // 任务列表数据
  const [list, setList] = useState(() => {
    return JSON.parse(localStorage.getItem('todoList')) || []
  })

  // 本地存储
  useEffect(() => {
    localStorage.setItem('todoList', JSON.stringify(list))
  }, [list])

  // 添加
  const addTodo = (name) => {
    setList([...list, { id: Date.now(), name, isDone: false }])
  }

  // 删除
  const delTodo = (id) => {
    setList(list.filter((item) => item.id !== id))
  }

  // 改变任务完成状态
  const handleDone = (id) => {
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            isDone: !item.isDone,
          }
        } else {
          return item
        }
      })
    )
  }

  // 修改名字
  const changeName = (id, name) => {
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            name,
          }
        } else {
          return item
        }
      })
    )
  }

  // 清空已完成
  const clearCompleted = () => {
    setList(list.filter((item) => item.isDone === false))
  }

  // 全选
  const allChecked = (e) => {
    setList(
      list.map((item) => {
        return {
          ...item,
          isDone: e.target.checked,
        }
      })
    )
  }

  return {
    list,
    addTodo,
    delTodo,
    handleDone,
    changeName,
    clearCompleted,
    allChecked,
  }
}

// 任务列表数据 放外面只执行一次 放App里面每次都会执行
// const todoList = JSON.parse(localStorage.getItem('todoList'))
function App() {
  // 根据完成状态显示任务列表
  const [type, setType] = useState('all')
  const {
    list,
    addTodo,
    delTodo,
    handleDone,
    changeName,
    clearCompleted,
    allChecked,
  } = useTodos()
  return (
    <Context.Provider value={{ delTodo, handleDone, changeName }}>
      <section className="todoapp">
        <TodoHeader addTodo={addTodo}></TodoHeader>
        <TodoMain list={list} type={type} allChecked={allChecked}></TodoMain>
        <TodoFooter
          list={list}
          type={type}
          setType={setType}
          clearCompleted={clearCompleted}
        ></TodoFooter>
      </section>
    </Context.Provider>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))
